<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="cu-nav-bar">
			<uni-nav-bar statusBar :title="pageTitle" color="#ffffff" backgroundColor="#07c160" left-icon="left"
				@clickLeft="goBackPage">
				<template v-slot:right>
					<uni-icons v-if="showDelete" type="trash" size="24" color="#ffffff" @click="delCashLog"></uni-icons>
				</template>
			</uni-nav-bar>
		</view>
		<!-- 分类 -->
		<zjw-button-group class="payType-group" :buttons="payTypeList" v-model="cashLogInfo.payType"
			bt-class="payType-group-bt" bt-select-class="payType-group-bt-ac" :disabled="payTypeDisabled"
			@click="changePayType">
		</zjw-button-group>
		<!-- 信息滚动区 -->
		<scroll-view class="scroll-view" scroll-y :scroll-top="scrollTop" :scroll-into-view="scrollToView">
			<!-- 金额 -->
			<view class="cashLog-money-view " @click="openCalculator()">
				<text :class="['money-icon', cashLogInfo.payType == 1 ? 'money-green':'money-red']">
					{{cashLogInfo.payType == 1 ? '￥' : '-￥'}}
				</text>
				<text :class="['money-content', cashLogInfo.payType == 1 ? 'money-green':'money-red']">
					{{ formatMoney(cashLogInfo.money) }}
				</text>
			</view>
			<!-- 收、支 分类 -->
			<zjw-button-group class="cashType-group" v-model="cashLogInfo.cashType" :buttons="cash_type_list_8"
				bt-class="cashType-group-bt" bt-select-class="cashType-group-bt-ac" optText="更多..."
				@clickOpt="openSelectCashTypeDialog" @longPress="openEditCashTypeDialog">
			</zjw-button-group>
			<!-- 使用账户 -->
			<view class="cashLog-item">
				<text class="item-label">{{cashLogInfo.payType == 1 ? '收款账户' : '付款账户'}}</text>
				<view class="cashLog-item-account-view">
					<image class="cashLog-account-icon" mode="aspectFit" :src="cashLogInfo.accountIcon"></image>
					<input class="cashLog-account-input" placeholder-class="item-input-placeholder"
						v-model="cashLogInfo.account" placeholder="点击选择账户" disabled @click="openSelectAccount(1)" />
				</view>
			</view>
			<!-- 收款账户 -->
			<view class="cashLog-item" v-if="cashLogInfo.payType == 3">
				<text class="item-label">收款账户</text>
				<view class="cashLog-item-account-view">
					<image class="cashLog-account-icon" mode="aspectFit" :src="cashLogInfo.account2Icon"></image>
					<input class="cashLog-account-input" placeholder-class="item-input-placeholder"
						v-model="cashLogInfo.account2" placeholder="点击选择账户" disabled @click="openSelectAccount(2)" />
				</view>
			</view>
			<!-- 备注 -->
			<view class="cashLog-item">
				<text class="item-label">备注</text>
				<textarea id="id_note" class="item-input-textarea" placeholder-class="item-input-placeholder"
					v-model="cashLogInfo.note" placeholder="点击添加备注,最好10字,最多50字" :maxlength="50"
					@keyboardheightchange="noteKeyboardEvent" />
			</view>
			<!-- 其他：日期，时间 -->
			<view class="cashLog-other" id="id_other">
				<view class="cashlog-date" @click="openSelectDate">
					<uni-dateformat :date="cashLogInfo.payTime" format="MM月dd日"></uni-dateformat>
					<text v-if="cashLogInfo.payTime_date == getNowDate()"> 今天</text>
				</view>
				<uni-dateformat class="cashlog-time" :date="cashLogInfo.payTime" format="hh:mm" @click="openSelectTime">
				</uni-dateformat>
			</view>
		</scroll-view>

		<!-- opt -->
		<view class="cashLog-btns" v-if="showSaveButton">
			<button class="btn-save" @click="saveCashLogData">保 存</button>
		</view>

		<!-- 计算器组件 -->
		<zjw-calculator ref="myCalculator" :initNumber="calculatorInitNumber" @confirm="confirmCalculator">
		</zjw-calculator>

		<!-- 通用选择器 -->
		<zjw-list-popup :title="selectDialog_Title" ref="selectDialog" :data="selectDialog_data"
			:enableLongPress='selectDialog_longPress' :opt-text="selectDialog_optText" @click="confirmSelected"
			@clickOpt="clickOptSelectDialog" @longPress="longPressSelectDialogItem">
		</zjw-list-popup>

		<!-- 普通弹窗：创建/修改分类 -->
		<uni-popup ref="addCashTypeDialog" type="center" :is-mask-click="false" :animation="false">
			<view class="addCashTypeDialog-page">
				<view class="addCashTypeDialog-top">
					<view class="addCashTypeDialog-title">{{addCashTypeDialogTitle}}</view>
					<uni-icons v-if="showDeleteCashType" type="trash" size="24" color="#ffffff"
						@click="delCashType"></uni-icons>
				</view>
				<view class="addCashTypeDialog-content">
					<!-- 分类 -->
					<zjw-button-group class="add-cashType-group" :buttons="payTypeList"
						v-model="addCashTypeDialogForm.payType" bt-class="add-cashType-group-bt"
						bt-select-class="add-cashType-group-bt-ac" :disabled="true">
					</zjw-button-group>
					<!-- 分类名称 -->
					<view class="addCashTypeDialog-content-cashType">
						<text class="cashType-label">分类名称</text>
						<view class="cashType-input-view">
							<image class="cashType-input-icon" mode="aspectFit" :src="addCashTypeDialogForm.icon"
								@click="openSelectDialog">
							</image>
							<input class="cashType-input" v-model="addCashTypeDialogForm.cashType"
								placeholder-class="cashType-input-place" placeholder="点击输入分类名称"
								:focus="addCashTypeDialogForm.id == 0"
								@keyboardheightchange="cashTypeDialogKeyboardEvent" />
						</view>
					</view>
					<!-- opt -->
					<view class="addCashTypeDialog-content-btns">
						<button class="ct-btn-cancel" @click="cancelSaveCashType">取 消</button>
						<button class="ct-btn-save" @click="saveCashTypeData">保 存</button>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 日期选择器 -->
		<zjw-calendar ref="myCalendar" v-model="cashLogInfo.payTime_date" @change="checkPayDate"></zjw-calendar>

		<!-- 时间选择器 -->
		<zjw-time-picker ref="myTimePicker" title="选择时间" v-model="cashLogInfo.payTime_time"
			indicatorClass="picker-selected" @change="checkPayTime">
		</zjw-time-picker>

	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		onUnmounted
	} from 'vue'
	import {
		onBackPress,
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import {
		getNowDate,
		getNowDateTime,
		getNowMonth,
		formatMoney
	} from '@/utils/utils.js'
	import {
		deleteCashLog,
		deleteCashType,
		getAllAccountList,
		getCashLogListForMonth,
		getCashTypeList,
		saveCashLog,
		saveCashType,
		updateCashLog,
		updateCashTypeName
	} from '@/service/service-api.js'
	import {
		gt,
		lt,
		gteq,
		lteq,
		eq
	} from '@/utils/math-utils'
	import {
		getCashTypeIconList
	} from '@/utils/cashtype-icon-utils'

	const pageTitle = ref('') // 弹出层：创建收支记录表单-标题
	const cashLogInfo = ref({}) // 收支记录表单数据
	const payTypeDisabled = ref(false) // 收支分类类型按钮状态
	const showDelete = ref(false) // 删除按钮状态
	const showSaveButton = ref(true) // 是否显示‘保存’按钮状态
	const currAccount = ref(1) // 当前操作账户
	const scrollTop = ref(0) // 滚动位置
	const scrollToView = ref("") // 滚动到某个视图

	const myCalculator = ref(null) // 计算器组件
	const calculatorInitNumber = ref('0') // 计算器组件初始值
	const cash_type_list = ref([]) // 交易分类列表
	const cash_type_list_8 = ref([]) // 交易分类列表 截取8
	const account_list = ref([]) // 分组账户列表
	const account_list_tem = ref([]) // 全账户账户列表

	const myCalendar = ref(null) // 日历选择器
	const myTimePicker = ref(null) // 时间选择器

	const selectDialog = ref(null) // 选择器弹窗
	const selectDialog_Title = ref('') // 选择器弹窗标题
	const selectDialog_data = ref([]) // 选择器弹窗数据
	const selectDialog_optText = ref('') // 选择器弹窗带操作按钮
	const selectDialog_longPress = ref(false) // 选择器弹窗,是否开启长按

	const addCashTypeDialog = ref(null) // 添加分类弹窗
	const addCashTypeDialogTitle = ref('') // 添加分类弹窗
	const addCashTypeDialogForm = ref({}) // 分类弹窗数据
	const showDeleteCashType = ref(false) // 删除按钮状态

	const payTypeList = [{
		label: '支 出',
		value: 2
	}, {
		label: '收 入',
		value: 1
	}, {
		label: '转 账',
		value: 3
	}]

	onLoad((e) => {
		let item = JSON.parse(e.logInfo);
		// 输入时不带正负
		let inputMoney = '0'
		if (item.money.startsWith('-')) {
			inputMoney = item.money.slice(1)
		} else {
			inputMoney = item.money
		}
		if (item.id == 0) {
			pageTitle.value = '创建交易'
			payTypeDisabled.value = false
			showDelete.value = false
			cashLogInfo.value = {
				'id': 0,
				'money': inputMoney, // 金额 (输入时不带正负，保存时添加正负)
				'account': '', // 账户名称 (使用账户名称,名称唯一)
				'payType': 2, // 1 收入、 2 支出、 3 转账
				'cashType': '', // 收支分类 (使用分类名称,名称唯一)
				'payTime': getNowDateTime(), // 收支时间
				'note': '', // 备注
				'account2': '', // 转账收款账户名称 (使用账户名称,名称唯一)
				'payTime_date': getNowDateTime().slice(0, 10),
				'payTime_time': getNowDateTime().slice(11, 16).split(':')
			}
			getAndFormatAccountList()
			if (account_list_tem.value.length > 0) {
				cashLogInfo.value.account = account_list_tem.value[0].name
				cashLogInfo.value.accountIcon = account_list_tem.value[0].icon
			} else {
				cashLogInfo.value.accountIcon = '/static/image/cash_type/jb.png'
			}
			getAndFormatCashTypeList(2)
			if (cash_type_list.value.length > 0) {
				cashLogInfo.value.cashType = cash_type_list.value[0].label
			}
			return
		}

		pageTitle.value = '修正交易'
		payTypeDisabled.value = true
		showDelete.value = true
		cashLogInfo.value = {
			'id': item.id,
			// 页面金额统一显示为正数，保存接口自动判断正负。
			'money': inputMoney, // 金额 (输入时不带正负，保存时添加正负)
			'account': item.account, // 账户名称 (使用账户名称,名称唯一)
			'payType': item.payType, // 1 收入、 2 支出、 3 转账
			'cashType': item.cashType, // 收支分类 (使用分类名称,名称唯一)
			'payTime': item.payTime, // 收支时间
			'note': item.note, // 备注
			'account2': item.account2, // 转账收款账户名称 (使用账户名称,名称唯一)
			'payTime_date': item.payTime.slice(0, 10),
			'payTime_time': item.payTime.slice(11, 16).split(':')
		}
		getAndFormatAccountList()
		let accountList = getAllAccountList()
		let findItem = accountList.find(item => item.name == cashLogInfo.value.account)
		if (findItem) {
			cashLogInfo.value.accountIcon = findItem.icon
		} else {
			cashLogInfo.value.accountIcon = '/static/image/cash_type/jb.png'
		}
		if (cashLogInfo.value.account2) {
			let findItem2 = accountList.find(item => item.name == cashLogInfo.value.account2)
			if (findItem2) {
				cashLogInfo.value.account2Icon = findItem2.icon
			} else {
				cashLogInfo.value.account2Icon = '/static/image/cash_type/jb.png'
			}
		}

		getAndFormatCashTypeList(item.payType, item.cashType)
	})

	// 滚动到底部
	const scrollToBottom = () => {
		nextTick(() => {
			scrollTop.value = Date.now()
		})
	}

	// 滚动到备注下面的视图:现在是时间：id_other
	const scrollToNoteViewAfter = () => {
		nextTick(() => {
			scrollToView.value = "id_other"
		})
	}

	// 获取并封装账户列表
	const getAndFormatAccountList = () => {
		// 获取并封装账户列表
		let accountList = getAllAccountList(0, 1)
		// 排序 (按使用频率)
		accountList.sort((a, b) => gt(b.sortNum, a.sortNum) ? 1 : -1)
		account_list_tem.value = accountList

		let account_list_cx = []
		let account_list_xy = []
		for (const item of accountList) {
			if (item.type == 1) {
				account_list_cx.push({
					label: item.name,
					value: item.name,
					icon: item.icon,
					desc: '￥' + item.money
				})
			} else {
				account_list_xy.push({
					label: item.name,
					value: item.name,
					icon: item.icon,
					desc: '￥' + item.money
				})
			}
		}

		let cx = {
			'group': '储蓄卡',
			'list': account_list_cx
		}
		let xy = {
			'group': '信用卡',
			'list': account_list_xy
		}
		account_list.value = [cx, xy]
	}

	// 获取并封装收支分类列表
	const getAndFormatCashTypeList = (payType, firstItem) => {
		// 获取收支分类列表
		let cashTypeList = getCashTypeList(payType)
		// 排序 (按使用频率)
		cashTypeList.sort((a, b) => gt(b.sortNum, a.sortNum) ? 1 : -1)

		let tem_list = []
		for (const item of cashTypeList) {
			tem_list.push({
				label: item.cashType,
				value: item.cashType,
				icon: item.icon
			})
		}
		if (firstItem && firstItem != '') {
			// 所属分类移动到第一位
			const new_tem_list = [
				...tem_list.filter(obj => obj.value == firstItem),
				...tem_list.filter(obj => obj.value != firstItem)
			];
			cash_type_list.value = new_tem_list
			cash_type_list_8.value = new_tem_list.slice(0, 8)
		} else {
			cash_type_list.value = tem_list
			cash_type_list_8.value = tem_list.slice(0, 8)
		}
	}

	// 打开计算器
	const openCalculator = () => {
		calculatorInitNumber.value = cashLogInfo.value.money
		myCalculator.value.open()
	}

	// 计算器组件-确认事件：计算结果 value
	const confirmCalculator = (value) => {
		// 创建交易记录页面的计算器组件-确认事件：计算结果 value
		// 这里只能正数，保存时，根据收支类型设置正负数;
		if (value.startsWith('-')) {
			value = value.slice(1)
		}
		cashLogInfo.value.money = value // 输入时不带正负，保存时添加正负
	}

	// 备注输入框：键盘高度改变时触发
	const noteKeyboardEvent = (e) => {
		let height = e.detail.height
		if (height > 0) {
			showSaveButton.value = false
			scrollToBottom()
		} else {
			showSaveButton.value = true
		}
	}

	// 收支分类输入框：键盘高度改变时
	const cashTypeDialogKeyboardEvent = (e) => {
		let height = e.detail.height
		if (height > 0) {
			showSaveButton.value = false
		} else {
			showSaveButton.value = true
		}
	}

	// 保存收支记录
	const saveCashLogData = () => {
		if (eq(cashLogInfo.value.money, '0')) {
			uni.showToast({
				icon: 'none',
				title: '交易金额不能为0'
			})
			return
		}

		if (cashLogInfo.value.account.trim() == '' ||
			(cashLogInfo.value.payType == 3 && cashLogInfo.value.account2.trim() == '')) {
			uni.showToast({
				icon: 'none',
				title: '请选择账户'
			})
			return
		}

		let payMoney = cashLogInfo.value.money
		// 1 收入、 2 支出、 3 转账 [支付时金额为负数，收入时金额为正数，转账时金额为正数]
		if (cashLogInfo.value.payType == 2 && gt(payMoney, '0')) {
			payMoney = '-' + payMoney
		}
		if (cashLogInfo.value.payType != 2 && lt(payMoney, '0')) {
			payMoney = payMoney.slice(1)
		}
		if (cashLogInfo.value.payType != 3) {
			cashLogInfo.value.account2 = ''
		}
		let resultData = {}
		if (cashLogInfo.value.id == 0) {
			resultData = saveCashLog(payMoney, cashLogInfo.value.account,
				cashLogInfo.value.payType, cashLogInfo.value.cashType, cashLogInfo.value.payTime,
				cashLogInfo.value.note, cashLogInfo.value.account2)
		} else {
			resultData = updateCashLog(cashLogInfo.value.id, payMoney,
				cashLogInfo.value.account, cashLogInfo.value.cashType, cashLogInfo.value.payTime,
				cashLogInfo.value.note, cashLogInfo.value.account2)
		}
		if (!resultData.success) {
			uni.showToast({
				icon: 'none',
				title: resultData.msg
			})
			return
		}

		// 操作成功，返回
		goBackPage()
	}

	// 删除收支记录
	const delCashLog = () => {
		if (cashLogInfo.value.id != 0) {
			let resultData = deleteCashLog(cashLogInfo.value.id)
			if (!resultData.success) {
				uni.showToast({
					icon: 'none',
					title: resultData.msg
				})
				return
			}
			// 操作成功，返回
			goBackPage()
		} else {
			uni.showToast({
				icon: 'none',
				title: '参数错误'
			})
		}
	}

	// 收支分类类型-按钮组: 点击事件
	const changePayType = (item) => {
		getAndFormatCashTypeList(item.value)
		if (cash_type_list.value.length > 0) {
			cashLogInfo.value.cashType = cash_type_list.value[0].label
		} else {
			cashLogInfo.value.cashType = ''
		}
	}

	// 打开日历弹窗
	const openSelectDate = () => {
		myCalendar.value.open()
	}

	// 日期选择器回调事件：确认选择日期
	const checkPayDate = (date) => {
		cashLogInfo.value.payTime = date + ' ' + cashLogInfo.value.payTime_time[0] + ':' +
			cashLogInfo.value.payTime_time[1] + ':00'
	}

	// 打开时间选择器
	const openSelectTime = () => {
		myTimePicker.value.open()
	}

	// 时间选择器回调事件：确认选择时间
	const checkPayTime = (time) => {
		cashLogInfo.value.payTime = cashLogInfo.value.payTime_date + ' ' + time[0] + ':' + time[1] + ':00'
	}

	// 打开账户选择器
	const openSelectAccount = (token) => {
		currAccount.value = token
		selectDialog_Title.value = '选择账户'
		selectDialog_data.value = account_list.value
		selectDialog_optText.value = ''
		selectDialog_longPress.value = false
		selectDialog.value.open()
	}

	// 打开收支分类选择器
	const openSelectCashTypeDialog = () => {
		selectDialog_Title.value = '选择分类'
		selectDialog_data.value = cash_type_list.value
		selectDialog_optText.value = '添加分类'
		selectDialog_longPress.value = true
		selectDialog.value.open()
	}

	// 通用选择器：确认选择
	const confirmSelected = (item) => {
		if (selectDialog_Title.value == '选择账户') {
			if (currAccount.value == 1) {
				cashLogInfo.value.account = item.value
				cashLogInfo.value.accountIcon = item.icon
			} else if (currAccount.value == 2) {
				cashLogInfo.value.account2 = item.value
				cashLogInfo.value.account2Icon = item.icon
			}
		} else if (selectDialog_Title.value == '选择分类') {
			cashLogInfo.value.cashType = item.value

			const find = cash_type_list_8.value.find(tem => tem.value == item.value)
			if (!find) {
				let new_cash_type_list_8 = [
					cash_type_list.value.find(a => a.value == item.value),
					...cash_type_list_8.value.filter(b => b.value != item.value)
				]
				cash_type_list_8.value = new_cash_type_list_8.slice(0, 8)
			}
		} else if (selectDialog_Title.value == '选择分类图标') {
			addCashTypeDialogForm.value.icon = item.icon
			if (addCashTypeDialogForm.value.cashType == '') {
				addCashTypeDialogForm.value.cashType = item.value
			}
		}
	}

	// 通用选择器: 长按事件
	const longPressSelectDialogItem = (item) => {
		if (selectDialog_Title.value == '选择分类') {
			openEditCashTypeDialog(item)
		}
	}

	// 通用选择器: '操作按钮'事件
	const clickOptSelectDialog = () => {
		if (selectDialog_Title.value == '选择分类') {
			openEditCashTypeDialog()
		}
	}

	// 打开选择分类图标
	const openSelectDialog = () => {
		let list = getCashTypeIconList()
		let bankIconList = []
		for (let item of list) {
			bankIconList.push({
				label: item.name,
				value: item.name,
				icon: item.icon,
			})
		}
		selectDialog_data.value = bankIconList
		selectDialog_Title.value = '选择分类图标'
		selectDialog_optText.value = ''
		selectDialog_longPress.value = false
		selectDialog.value.open()
	}

	// 打开编辑分类信息弹窗
	const openEditCashTypeDialog = (item) => {
		if (item) {
			let cashTypeList = getCashTypeList(cashLogInfo.value.payType)
			let row = cashTypeList.find(a => a.cashType == item.label)
			if (row) {
				addCashTypeDialog.value.open()
				addCashTypeDialogTitle.value = '编辑分类'
				showDeleteCashType.value = true
				addCashTypeDialogForm.value = {
					'id': row.id, // 唯一id，这里用时间戳
					'pid': row.pid, // 上级id [最大二级]
					'payType': row.payType, // 1 收入、 2 支出、 3 转账
					'cashType': row.cashType, // 收支分类
					'status': row.status, // 状态 1 可用 2 不可用
					'isDelete': row.isDelete, // 状态 1 已删除 0 正常 【删除时，同时设置不可用】
					'icon': row.icon
				}
			} else {
				uni.showToast({
					icon: 'none',
					title: '分类不存在'
				})
			}
		} else {
			addCashTypeDialog.value.open()
			addCashTypeDialogTitle.value = '添加分类'
			showDeleteCashType.value = false
			addCashTypeDialogForm.value = {
				'id': 0, // 唯一id，这里用时间戳
				'pid': 0, // 上级id [最大二级]
				'payType': cashLogInfo.value.payType, // 1 收入、 2 支出、 3 转账
				'cashType': '', // 收支分类
				'status': 1, // 状态 1 可用 2 不可用
				'isDelete': 0, // 状态 1 已删除 0 正常 【删除时，同时设置不可用】
				'icon': '/static/image/cash_type/jb.png'
			}
		}
	}

	// 关闭分类弹窗
	const cancelSaveCashType = () => {
		addCashTypeDialog.value.close()
	}

	// 保存分类
	const saveCashTypeData = () => {
		addCashTypeDialogForm.value.cashType = addCashTypeDialogForm.value.cashType.trim()
		if (addCashTypeDialogForm.value.cashType == '') {
			uni.showToast({
				icon: 'none',
				title: '分类名称不能为空'
			})
			return
		}
		// 默认图标
		if (addCashTypeDialogForm.value.icon == '') {
			addCashTypeDialogForm.value.icon = '/static/image/cash_type/jb.png'
		}

		let resultData
		if (addCashTypeDialogForm.value.id > 0) {
			resultData = updateCashTypeName(addCashTypeDialogForm.value.id,
				addCashTypeDialogForm.value.cashType, addCashTypeDialogForm.value.icon)
		} else {
			resultData = saveCashType(addCashTypeDialogForm.value.pid, addCashTypeDialogForm.value.payType,
				addCashTypeDialogForm.value.cashType, addCashTypeDialogForm.value.icon)
		}

		if (!resultData.success) {
			uni.showToast({
				icon: 'none',
				title: resultData.msg
			})
			return
		}
		// 刷新列表
		cashLogInfo.value.cashType = addCashTypeDialogForm.value.cashType
		getAndFormatCashTypeList(addCashTypeDialogForm.value.payType, addCashTypeDialogForm.value.cashType)

		addCashTypeDialog.value.close()
	}

	// 删除分类
	const delCashType = () => {
		if (addCashTypeDialogForm.value.id > 0) {
			let resultData = deleteCashType(addCashTypeDialogForm.value.id)
			if (!resultData.success) {
				uni.showToast({
					icon: 'none',
					title: resultData.msg
				})
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: '无效数据'
			})
		}
		// 刷新列表
		getAndFormatCashTypeList(addCashTypeDialogForm.value.payType)
		addCashTypeDialog.value.close()
	}

	// 返回
	const goBackPage = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
	@import url("cash_log_info.css");
</style>